﻿using System;
using System.Data.Common;
using System.Web;
using Library.OrmEnterpriseEntity.Factor;

namespace Library.OrmEnterpriseEntity {
	/// <summary>
	/// Sql connection manager class
	/// </summary>
	public class ConnectionManager : IDisposable {
		private static readonly ConnectionManager Empty = new EmptyConnection();
		private const string Key = "Library.OrmEnterpriseEntiry.ConnectionManager";
		internal DbConnection Connection { get; private set; }
		internal TransactionManager TransactionManager { get; set; }
		[ThreadStatic]
		private static ConnectionManager _connectionManager;
		internal static ConnectionManager Current {
			get {
				ConnectionManager con;
				var context = HttpContext.Current;
				if (context != null) {
					con = context.Items[Key] as ConnectionManager;

					if (con == null) {
						con = new ConnectionManager();
						HttpContext.Current.Items[Key] = con;
					}
				} else {
					con = _connectionManager;
					if (con == null) {
						con = new ConnectionManager();
						_connectionManager = con;
					}

				}
				return con;
			}
		}

		/// <summary>
		/// Begin scope using one connection to DBMS
		/// </summary>
		/// <returns></returns>
		public static ConnectionManager OneConnectionScope() {
			ConnectionManager current = Current;
			if (current.Connection != null || TransactionManager.GetCurrentTran() != null) {
				// exist connection, no need to create new connection
				return Empty;
			}

			current.Connection = DbContext.Instance.Context.CreateConnection();
			current.Connection.Open();
			return current;
		}
		private ConnectionManager() {

		}
		public virtual void Dispose() {
			if (Connection != null && TransactionManager == null) {
				Connection.Close();
				Connection = null;
			}
		}

		private class EmptyConnection : ConnectionManager {
			public override void Dispose() {

			}
		}
	}
}
